import React, { Component } from 'react';
import { connect } from 'dva';

import { Form, Input, Button, notification, Col, Row, message, Cascader } from 'antd';
import { UmiComponentProps, FormComponentProps } from '@/common/type';

import { DICT } from '../enum'

import { DividerItem } from '@/components/DividerItem';
import { fomatter } from '@/utils/formatter';
import { DropDownSelect } from '@/components/DropDownSelect';

const { TextArea } = Input;

interface P {
  data?: {
    id?: string;
    buildId?: string; floorId?: string; areaId?: string;
    buildName?: string; floorName?: string; areaName?: string;
    deviceTypeName?: string; deviceType?: string;
  },
  location?: Array<any>;
  type?: Array<any>;
  dict?: any;
  image?: string;
  lLocation?: boolean;
  lType?: boolean;
}
type Props = P & UmiComponentProps & FormComponentProps;

@connect(({ fire_facilities, loading }) => ({
  dict: fire_facilities.dict || {},
  location: fire_facilities.location || [],
  type: fire_facilities.type || [],
  lLocation: loading.effects['fire_facilities/queryLocation'],
  lType: loading.effects['fire_facilities/queryType'],
}))
class FormItem extends Component<Props, any> {
  state = {
    show: false,
    tmpLocation: null
  };

  componentDidMount() {
    const { data, form, dispatch } = this.props;

    dispatch({
      type: 'fire_facilities/init', payload: {
        dict: { keyList: DICT },
      }
    })
    if (data) {
      const {
        buildId, floorId, areaId,
        buildName, floorName, areaName,
        deviceTypeName,
        deviceType,
        ...res
      } = data;

      form.setFieldsValue({
        // buildList: [buildId, floorId, areaId],
        ...res
      })
    }
  }

  handleMap = () => {
    const { form, data } = this.props;
    const { getFieldValue } = form;

    const list = getFieldValue('buildList');
    if ((!Array.isArray(list) || !list[1]) && !data.floorId) {
      message.warn('请选择楼层');
      return;
    }
  }


  handleSubmit = (e: Event) => {
    e.preventDefault();

    const { dispatch, form, data } = this.props;
    form.validateFields((err: undefined | {}, values: any) => {
      if (!err) {
        const res = FOMMATER.map(v => fomatter(
          values[v.list],
          data ? v.names.map(u => data[u]) : null,
          v.len,
          v.names
        ))

        const flag = FOMMATER.every(v => !!v);
        if (!flag) {
          notification['error']({
            message: `保存失败`,
            description: '信息录入不规范',
          });
          return;
        }

        let params = {
          ...values,
        };

        res.forEach(v => {
          params = {
            ...v,
            ...params,
          }
        })

        data && data.id ? dispatch({
          type: 'fire_facilities/update',
          payload: {
            id: data.id,
            ...params
          },
        }) : dispatch({
          type: 'fire_facilities/create',
          payload: params
        })

      } else {
        notification['error']({
          message: `保存失败`,
          description: '信息录入不规范',
        });
      }
    })
  };

  loadData = (type, selectedOptions) => {

    const { dispatch } = this.props;
    const targetOption = selectedOptions[selectedOptions.length - 1];
    targetOption.loading = true;
    dispatch({
      type: `fire_facilities/${type}`,
      payload: {
        target: {
          id: targetOption.value.split('%%')[0],
          ind: targetOption.value.split('%%')[1],
        },
        option: selectedOptions.map(v => (v.value.split('%%')[1]))
      }
    })
  };

  render() {
    const { form, data, dict = {} } = this.props;
    const { getFieldDecorator } = form;

    console.log(this.props.location)

    const formItemLayout = {
      labelCol: {
        xs: { span: 12 },
        sm: { span: 6 },
      },
      wrapperCol: {
        xs: { span: 6 },
        sm: { span: 14 },
      },
    };

    const noItemLayout = {
      wrapperCol: { span: 14, offset: 6 },
    };

    const Info = DividerItem(data && data.id ? 'form' : 'plus', '消防设施器材')

    const ButtonList = () => (
      <Form.Item>
        <Button style={{ marginLeft: 20 }} onClick={() => {
          window.history.back()
        }}>取消</Button>
        <Button type="primary"
          htmlType="submit"
          style={{ marginLeft: 20 }}
          onClick={(e: any) => {
            this.handleSubmit(e)
          }}
        >保存</Button>
      </Form.Item>
    )

    return (
      <Form>
        <Info />
        <Row style={{ minHeight: '75vh' }}>
          <Col span={12}>
            <Form.Item
              {...formItemLayout}
              label="名称"
            >
              {getFieldDecorator('name', {
                rules: [{
                  required: true, message: '请输入名称',
                }],
              })(
                <Input placeholder='请输入名称' />
              )}
            </Form.Item>
            <Form.Item
              {...formItemLayout}
              label='所在位置'
              required
            >
              {getFieldDecorator('buildList')(
                <Cascader
                  // disabled={!!(data && data.id)}
                  options={this.props.location}
                  loadData={this.loadData.bind(this, 'queryLocation')}
                  changeOnSelect={this.props.lLocation}
                  placeholder={data ? `${data.buildName || ''}${data.floorName || ''}${data.areaName || ''}` : '请选择'}
                />
              )}
            </Form.Item>
            <Form.Item
              {...noItemLayout}
            >
              {getFieldDecorator('address', {
                rules: [{ required: true, message: '请输入详细地址' }],
              })(
                <TextArea rows={4} style={{ width: '100%', marginTop: '-15px' }} />
              )}
            </Form.Item>
            <Form.Item
              {...formItemLayout}
              label='类型'
              required
            >
              {getFieldDecorator('typeList')(
                <Cascader
                  options={this.props.type}
                  loadData={this.loadData.bind(this, 'queryType')}
                  changeOnSelect={this.props.lType}
                  placeholder={data ? `${data.deviceTypeName || ''}` : '请选择'}
                />
              )}
            </Form.Item>
            <Form.Item
              label="状态"
              {...formItemLayout}
            >
              {getFieldDecorator('status', {
                rules: [{ required: true, message: '请选择状态' }],
              })(
                DropDownSelect(dict, 'device.status')
              )}
            </Form.Item>
            <Form.Item
              {...formItemLayout}
              label='厂家型号'
            >
              {getFieldDecorator('product')(
                <Input placeholder='请输入厂家型号' />
              )}
            </Form.Item>
          </Col>
        </Row>
        <Row><ButtonList /></Row>
      </Form >
    );
  }
}

const FormList = Form.create<Props>()(FormItem);
export default FormList;

const FOMMATER = [{
  names: ['buildId', 'floorId', 'areaId'],
  list: 'buildList',
  len: 2
}, {
  names: ['systemId', 'deviceType'],
  list: 'typeList',
  len: 2
}]